 /*
 * UMLSynch - VPSDE plugin part
 * http://umlsynch.googlecode.com
 *
 * Copyright 2008-2010, Evgeny Alexeyev
 * Licensed under the EPL - v1.0
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */

package com.googlecode.umlsynch.vpsde.rpc;

import com.googlecode.umlsynch.rpc.TEditorRpc;
import com.googlecode.umlsynch.rpc.TEditorRpcDispatcher;
import com.googlecode.umlsynch.rpc.TFinderRpc;
import com.googlecode.umlsynch.rpc.TFinderRpcDispatcher;
import com.googlecode.umlsynch.rpc.TIndexerRpc;
import com.googlecode.umlsynch.rpc.TIndexerRpcDispatcher;
import com.googlecode.umlsynch.rpc.TUMLEditor;
import com.googlecode.umlsynch.rpc.TUMLEditorDispatcher;
import com.googlecode.umlsynch.rpc.base.IDebug;
import com.googlecode.umlsynch.rpc.base.TConfig;
import com.googlecode.umlsynch.rpc.base.TDebug;
import com.googlecode.umlsynch.rpc.base.TDispatcherManager;
import com.googlecode.umlsynch.rpc.base.TIOHandler;

public class Server {
	private TConfig cfg;
	private TDispatcherManager dm;
	private Thread thread;
	private TDebug debug;
	public boolean activatedFlag = false;

	public Server (TConfig vpsde, IDebug dbg) {
		debug = new TDebug(dbg);
		dm = new TDispatcherManager(debug);
		cfg = vpsde;

		if (cfg == null)
			return; 

		if (thread == null) {
			thread = new Thread() {
				public void run() {
					// UMLEditor interface implementation
					TUMLEditor erpc = new TUMLEditor();
					// UMLEditor interface dispatching
					TUMLEditorDispatcher erpcd = new TUMLEditorDispatcher(debug, dm, erpc);
					
					// May be it was not a good idea to 
					// porvide DiagramManager as argument
					// because now I can see warnings about unused variables

					// Handling of input/output 
					TIOHandler ioh = new TIOHandler(cfg, debug);
					
					// Create Server Socket
					if (!ioh.ServerConnect()) {
						debug.Error("Failed to open server socket");
						activatedFlag = true;
						return;
					}
					// Server socket activated- flag 
					activatedFlag = true;
					
					// loop an accept-process cycle 
					// dm.process close socket on each iteration
					// it is allow to accept requests from different 
					// client:
					while (ioh.accept()) {
						dm.process(ioh);	
					}

					debug.Error("Exit from dispatcher manager thread");
				}
			};
			thread.start();
		}

	}
}
